package completable;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.*;
@Slf4j
public class AskPriceDemo {

    /* ---------- 模拟远程报价 ---------- */
    static class QuoteTask implements Callable<Integer> {
        private final String supplier;
        private final int randomBound;   // 报价上限
        private final int costMs;        // 模拟网络耗时

        QuoteTask(String supplier, int randomBound, int costMs) {
            this.supplier = supplier;
            this.randomBound = randomBound;
            this.costMs = costMs;
        }

        @Override
        public Integer call() throws Exception {
            Thread.sleep(costMs);
            int price = new Random().nextInt(randomBound) + 1;
            System.out.printf("%s 报价 %d 元（耗时 %d ms）%n", supplier, price, costMs);
            return price;
        }

        public static void main(String[] args) throws  Exception {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            CompletionService<Integer> cs = new ExecutorCompletionService<>(pool);
            cs.submit(new QuoteTask("suA", 211, 160));
            cs.submit(new QuoteTask("suA", 47, 557));
            cs.submit(new QuoteTask("suA", 99, 1024));

            int bestPrice = Integer.MAX_VALUE;
            int received = 0;

            while(received < 3) {
                Future<Integer> f = cs.take();
                int price = f.get();
                if (price < bestPrice) {
                    bestPrice = price;
                }
                received++;
            }
            log.info(">>>最低报价:{}", bestPrice);

            pool.shutdown();
    }
    }
}
